﻿using OD.ProjectCustomizationTool.Helpers;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace OD.ProjectCustomizationTool.Tools
{
    internal sealed class DocumentationFileSetter : ProjectUpdaterBase, IFlatFileUpdate
    {
        protected override void InternalUpdate()
        {   // Nothing to do here.
        }

        void IFlatFileUpdate.Update()
        {
            using (var monitor = new FlatProjectFileUpdateMonitor(this))
            {
                var releasePropertyGroup = monitor.GetConditionnedProperty(Properties.Resources.ReleaseProjectProperty);
                var documentationFileNode = (from element in releasePropertyGroup.Elements()
                                             where String.Equals(element.Name.LocalName, Properties.Resources.DocumentationFileProjectProperty)
                                             select element).FirstOrDefault();

                if (this.ProjectTypes.Contains(EProjectType.Test))
                {
                    if (documentationFileNode != null)
                    {
                        this.Monitor.Logger.WriteLine("Removing documentation in configuration '" + Properties.Resources.ReleaseProjectProperty + "'");
                        documentationFileNode.Remove();
                    }
                }
                else
                {
                    if (documentationFileNode == null)
                    {
                        documentationFileNode = new XElement(XName.Get(Properties.Resources.DocumentationFileProjectProperty));
                        releasePropertyGroup.Add(documentationFileNode);
                    }

                    var outputPathNode = (from element in releasePropertyGroup.Elements()
                                          where String.Equals(element.Name.LocalName, Properties.Resources.OutputPathProjectProperty)
                                          select element).FirstOrDefault();
                    var rootNamespace = this.CurrentProject.GetPropertyValue(Properties.Resources.RootNamespaceProjectProperty);
                    var value = Path.Combine(outputPathNode.Value, rootNamespace + ".xml");

                    if (!String.Equals(documentationFileNode.Value, value))
                    {
                        this.Monitor.Logger.WriteLine("Declaring documentation in configuration '" + Properties.Resources.ReleaseProjectProperty + "'");
                        documentationFileNode.Value = value;
                    }
                }
            }
        }
    }
}
